/**
 * 
 */
package org.pandazxx.picasamanager.io;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Vector;

import org.apache.log4j.Logger;

/**
 * @author pandazxx
 *
 */
public class InputStreamIntercepter extends InputStream {
	private static final Logger logger = Logger.getLogger(InputStreamIntercepter.class);
	
	private InputStream inputStream;
	
	private List<InputStreamListener> listeners = new Vector<InputStreamListener>();
	
	public InputStreamIntercepter(InputStream is) {
		inputStream = is;
	}
	
	public InputStreamIntercepter addListener(InputStreamListener listener) {
		this.listeners.add(listener);
		return this;
	}
	

	/* (non-Javadoc)
	 * @see java.io.InputStream#available()
	 */
	@Override
	public int available() throws IOException {
		// TODO Auto-generated method stub
		return inputStream.available();
	}

	/* (non-Javadoc)
	 * @see java.io.InputStream#close()
	 */
	@Override
	public void close() throws IOException {
		logger.debug("Close!");
		for (InputStreamListener listener : listeners) {
			listener.closeStream();
		}
		
		inputStream.close();
	}

	/* (non-Javadoc)
	 * @see java.io.InputStream#mark(int)
	 */
	@Override
	public synchronized void mark(int arg0) {
		// TODO Auto-generated method stub
		inputStream.mark(arg0);
	}

	/* (non-Javadoc)
	 * @see java.io.InputStream#markSupported()
	 */
	@Override
	public boolean markSupported() {
		// TODO Auto-generated method stub
		return inputStream.markSupported();
	}

	/* (non-Javadoc)
	 * @see java.io.InputStream#read(byte[], int, int)
	 */
	@Override
	public int read(byte[] arg0, int arg1, int arg2) throws IOException {
		int ret = inputStream.read(arg0, arg1, arg2);
		for (InputStreamListener listener : listeners) {
			listener.readFromStream(ret >=0 ? ret : 0);
			if (ret == -1) {
				listener.readOnEnd();
			}
		}
		return ret;
	}

	/* (non-Javadoc)
	 * @see java.io.InputStream#read(byte[])
	 */
	@Override
	public int read(byte[] arg0) throws IOException {
		int ret = inputStream.read(arg0);
		for (InputStreamListener listener : listeners) {
			listener.readFromStream(ret >=0 ? ret : 0);
			if (ret == -1) {
				listener.readOnEnd();
			}
		}
		return ret;
	}

	/* (non-Javadoc)
	 * @see java.io.InputStream#reset()
	 */
	@Override
	public synchronized void reset() throws IOException {
		// TODO Auto-generated method stub
		inputStream.reset();
	}

	/* (non-Javadoc)
	 * @see java.io.InputStream#skip(long)
	 */
	@Override
	public long skip(long arg0) throws IOException {
		// TODO Auto-generated method stub
		return inputStream.skip(arg0);
	}

	/* (non-Javadoc)
	 * @see java.io.InputStream#read()
	 */
	@Override
	public int read() throws IOException {
		int ret = inputStream.read();
		for (InputStreamListener listener : listeners) {
			listener.readFromStream(ret >=0 ? 1 : 0);
			if (ret == -1) {
				listener.readOnEnd();
			}
		}
		return ret;
	}

}
